package ni;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

import main.ChatNI;

/**
 * Send a fileMessage
 * Package  ni
 * Project ChatSystemG5 - INSA 4INFOA1 - 2013/2014
 * @author Thomas Vuillemin Martin Conant
 */
public class TcpSender extends Tcp{
	
	
	private Socket socket;
	private OutputStreamWriter writer;
	private Object message;
	private File file;
	private InetAddress adressee;

	
	/**
	 * Constructor of TcpSender
	 * @param ni the ChatNI object
	 * @param file the File to be send
	 * @param adresee the InetAddress of the adresee user
	 */
	public TcpSender(ChatNI ni, File file, InetAddress adresee) {
		super(ni);
		socket=null;
		this.file = file;
		this.adressee = adresee;
	}
	
	/**
	 * Run method
	 * Open a Socket, send the file on this socket and then close the socket.
	 */
	@Override
	public void run() {
		try {
			this.socket=new Socket(adressee,ni.PORTfichier);
			byte[] buffer = new byte[(int) file.length()];
			int number;
			System.out.println("TcpSender : Socket Open");
			FileInputStream fileInputStream = new FileInputStream(file);
			BufferedOutputStream socketOutputStream = new BufferedOutputStream(socket.getOutputStream());
			while ((number = fileInputStream.read(buffer)) != -1) {
			    socketOutputStream.write(buffer, 0, number);
			}
			System.out.println("TcpSender : File send");
			socketOutputStream.close();
			fileInputStream.close();
			System.out.println("TcpSender : socket close");
		} catch(IOException e) {
			System.out.println("TcpSender : could not send fileMessage");
		}
		try {
			socket.close();
		} catch (IOException e) {
			System.out.println("TcpSender : could not close socket");
		}
		
	}

}
